/**
 * 根据message派发命令
 *
 * @param {object} handlers - 命令映射
 * @param {function} command - 派发的命令函数
 */
function useCommandHandlers(handlers) {
  return (message, socket, request) => {
    const [command, rtspStr] = checkoutCommand(message, handlers);
    if (!command) return;
    command(checkoutRtspStr(rtspStr), socket, request);
  };
}

/**
 *  命令校验-从字符串开头获取命令
 *
 * @param {string} str
 * @param {object} commands 命令对象
 * @returns {[function, string] | []} - 返回 [ 命令, rtsp字符串 ]
 */
function checkoutCommand(str, commands) {
  str = str.trim();
  const command = Object.keys(commands).find((command) =>
    str.startsWith(command)
  );
  if (!command) return [];
  const rtspStr = str.replace(command, "").trim();
  return [commands[command], rtspStr];
}

/**
 * 校验rtsp地址
 *
 * @param {string} str
 * @returns {string[]} rtsp地址数组
 */
const regex = /^rtsp:\/\/(.+?):(.*?)@(.*?)(?::(\d+))?\/(.*)$/;
function checkoutRtspStr(str) {
  let result = [];
  // 是否json数组
  try {
    result = JSON.parse(str);
    if (!Array.isArray(result)) throw new Error("只接受数组");
  } catch (error) {
    // 是否逗号分割
    const split = str.split(",");
    if (result.length > 1) {
      result = split;
    } else {
      // 是否单地址
      result = [str];
    }
  }
  return result
    .map((str) => str.trim())
    .filter((rtsp) => regex.test(rtsp.trim()));
}

module.exports = { useCommandHandlers };
